#!/usr/bin/perl -w
use strict;
use Getopt::Long;

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

my $usage = <<'USAGE';

USAGE:

    dialign_helper.pl prot.fa > multiply_aligned.fa


USAGE



sub run_cmd
{
	#remove beginning white space and new lines
	my $cmd = $_[0];
	$cmd =~tr/\t\n/ /d;
	$cmd =~ s/\s+/ /gm;
	if ($_[1])
	{
		print STDERR $cmd;
	}
	system $cmd and die "Failed [ $cmd ]\n$!\n";
}


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory

# optional parameters
my $help;
GetOptions(
			'help'					=> \$help);

die $usage if ($help || @ARGV != 1);
my $orig_file = $ARGV[0];

run_cmd(<<CMD);
	export DIALIGN2_DIR=/net/cpp-group/bin/dialign2_dir;
	/net/cpp-group/bin/dialign2_dir/dialign2-2 -fn $orig_file.temp.dialign -fa $orig_file
CMD


sub get_orig_accessions($)
{
	my ($orig_file) = @_;
	open ORIG, $orig_file or die;
	my @accessions;
	while (<ORIG>)
	{
		next unless /^>/;
		push(@accessions,  $_);
	}
	return @accessions;
}

sub substitute_accessions($\@)
{
	my ($file, $accessions) = @_;
	open FILE, $file or die;

	my $acc_cnt = 0;
	while (<FILE>)
	{
		next unless /\S+/;
		unless (/^>/)
		{
			print ;
			next;
		}

		if ($acc_cnt > @$accessions)
		{
			die "Error:\n\tMore sequences in dialign output ($acc_cnt) than in original FASTA file.";
		}
		print $accessions->[$acc_cnt++];
	}

	die "Error:\n\tFewer sequences in dialign output ($acc_cnt) than in original FASTA file." unless $acc_cnt == @$accessions;
}


my @accessions = get_orig_accessions($orig_file);
substitute_accessions("$orig_file.temp.dialign.fa", @accessions);

#unlink("$orig_file.temp.dialign");
#unlink("$orig_file.temp.dialign.fa");
